package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.domain.FamilyMemberElder;
import com.zzyl.nursing.dto.DeviceDataListByDayRequestDto;
import com.zzyl.nursing.dto.DevicePropertyStatusRequestDto;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.dto.AddElderRequestDto;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.ElderMapper;
import com.zzyl.nursing.mapper.FamilyMemberElderMapper;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.nursing.vo.LoginVo;
import com.zzyl.nursing.vo.propertyStatusInfo;
import com.zzyl.nursing.vo.ServicePropertiesVo;
import com.zzyl.nursing.vo.DeviceDataListByDayRequestVo;
import com.zzyl.nursing.vo.DeviceDataListByWeekRequestVo;
import com.zzyl.nursing.vo.FamilyElderListVo;
import com.zzyl.nursing.vo.FamilyMemberElderVo;
import com.zzyl.nursing.vo.MemberElderVo;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.text.SimpleDateFormat;
import java.util.stream.Collectors;
import java.util.Comparator;
import java.time.LocalDate;

/**
 * 老人家属Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-09-19
 */
@Service
@Slf4j
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper,FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private WechatService wechatService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;

    static List<String> DEFAULT_NICK_NAME = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝");

    /**
     * 小程序登录
     *
     * @param dto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto dto) {

        //1.获取openid(调用微信的接口获取) ***
        String openid = wechatService.getOpenid(dto.getCode());

        //2.根据openid查询用户
        LambdaQueryWrapper<FamilyMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FamilyMember::getOpenId,openid);
        FamilyMember familyMember = getOne(queryWrapper);

        //3.判断用户是否存在，用户不存在，就构建用户
        if(ObjectUtil.isEmpty(familyMember)){
            /*familyMember = new FamilyMember();
            familyMember.setOpenId(openid);*/
            familyMember = FamilyMember.builder()
                    .openId(openid)
                    .build();
        }

        //4.获取用户的手机号（调用微信的接口获取）***
        String phone = wechatService.getPhone(dto.getPhoneCode());

        //5. 新增或修改用户
        inserOrUpdateFamilyMember(familyMember,phone);

        //6. 把用户的信息封装到token,返回
        Map<String,Object> claims = new HashMap<>();
        claims.put("username",familyMember.getName());
        claims.put("userId",familyMember.getId());
        String token = tokenService.createToken(claims);

        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(familyMember.getName());

        return loginVo;
    }

    /**
     * 新增或修改用户
     * @param familyMember
     * @param phone
     */
    private void inserOrUpdateFamilyMember(FamilyMember familyMember, String phone) {

        //1. 判断新的手机跟数据库中保存的手机号是否一致
        if(ObjectUtil.notEqual(familyMember.getPhone(),phone)){
            familyMember.setPhone(phone);
        }

        //2. id是否存在，如存在，就修改
        if(ObjectUtil.isNotEmpty(familyMember.getId())){
            updateById(familyMember);
            return;
        }

        //3. 不存在，就新增 (拼装用户的昵称：随机字符串+手机号后4位)
        int index = (int)(Math.random() * DEFAULT_NICK_NAME.size());
        String nickName = DEFAULT_NICK_NAME.get(index)+ phone.substring(phone.length()-4);
        familyMember.setName(nickName);
        save(familyMember);

    }

    /**
     * 查询健康数据
     * @param iotId
     * @return
     */
    @Override
    public List<ServicePropertiesVo> queryServiceProperties(String iotId) {
        // 从Redis中获取设备数据
        log.info("iotId:{}",iotId);
        String jsonStr = (String) redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_LAST_DATA, iotId);
        log.info("jsonStr:{}",jsonStr);
        // 如果数据为空，返回空列表
        if (StringUtils.isEmpty(jsonStr)) {
            return ListUtil.of();
        }
        
        // 处理可能的字符串包装问题：去除外层引号
        String cleanJsonStr = jsonStr.trim();
        if (cleanJsonStr.startsWith("\"") && cleanJsonStr.endsWith("\"") && cleanJsonStr.length() > 2) {
            log.info("检测到JSON字符串被双引号包装，去除外层引号...");
            cleanJsonStr = cleanJsonStr.substring(1, cleanJsonStr.length() - 1);
            // 处理可能的转义字符
            cleanJsonStr = cleanJsonStr.replace("\\\"", "\"");
            log.info("处理后的JSON: {}", cleanJsonStr.substring(0, Math.min(200, cleanJsonStr.length())) + "...");
        }
        
        // 将JSON字符串转换为DeviceData列表
        List<DeviceData> deviceDataList;
        try {
            // 检查是否是数组格式
            if (cleanJsonStr.trim().startsWith("[")) {
                // 是数组格式，直接解析
                deviceDataList = JSONUtil.toList(cleanJsonStr, DeviceData.class);
            } else if (cleanJsonStr.trim().startsWith("{")) {
                // 是单个对象格式，先转换成数组再解析
                deviceDataList = JSONUtil.toList("[" + cleanJsonStr + "]", DeviceData.class);
            } else {
                log.warn("无效的JSON格式: {}", cleanJsonStr);
                return ListUtil.of();
            }
        } catch (Exception e) {
            log.error("解析设备数据失败: {}, 数据: {}", e.getMessage(), cleanJsonStr);
            log.error("异常详情: ", e);
            // 临时解决方案：手动解析JSON
            try {
                log.info("尝试手动解析JSON数据...");
                List<DeviceData> manualParsedList = parseDeviceDataManually(cleanJsonStr);
                if (!manualParsedList.isEmpty()) {
                    log.info("手动解析成功，数据条数: {}", manualParsedList.size());
                    deviceDataList = manualParsedList;
                } else {
                    return ListUtil.of();
                }
            } catch (Exception ex) {
                log.error("手动解析也失败: {}", ex.getMessage());
                return ListUtil.of();
            }
        }
        
        log.info("deviceDataList:{}",deviceDataList);

        // 将DeviceData转换为ServicePropertiesVo
        return deviceDataList.stream().map(deviceData -> {
            ServicePropertiesVo vo = new ServicePropertiesVo();
            vo.setFunctionId(deviceData.getFunctionId());
            vo.setValue(deviceData.getDataValue());
            
            // 将alarmTime转换为字符串格式 "yyyy-MM-ddTHH:mm:ss"
            if (deviceData.getAlarmTime() != null) {
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
                vo.setEventTime(deviceData.getAlarmTime().format(formatter));
            }
            log.info("vo:{}",vo);
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * 查询健康数据（旧版）
     * @param dto
     * @return
     */
    @Override
    public List<ServicePropertiesVo> queryDevicePropertyStatus(DevicePropertyStatusRequestDto dto) {
        log.info("dto:{}",dto);
        propertyStatusInfo propertyStatusInfo = new propertyStatusInfo();
        //查询redis中是否存在数据
        String jsonStr = (String) redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_LAST_DATA, dto.getDeviceName());
        log.info("jsonStr:{}",jsonStr);
        if(StringUtils.isEmpty(jsonStr)){
            return ListUtil.of();
        }
        

        return null;
    }

    @Autowired
    private DeviceDataMapper deviceDataMapper;
    /**
     * 按天统计查询指标数据
     * @param dto
     * @return
     */
    @Override
    public List<DeviceDataListByDayRequestVo> queryDeviceDataListByDay(DeviceDataListByDayRequestDto dto) {
        log.info("dto:{}",dto);
        
        // 判断时间戳是秒级还是毫秒级
        LocalDateTime startTime, endTime;
        if (dto.getStartTime() > 1000000000000L) {
            // 毫秒级时间戳
            startTime = LocalDateTime.ofEpochSecond(dto.getStartTime() / 1000, 0, java.time.ZoneOffset.ofHours(8));
            endTime = LocalDateTime.ofEpochSecond(dto.getEndTime() / 1000, 0, java.time.ZoneOffset.ofHours(8));
        } else {
            // 秒级时间戳
            startTime = LocalDateTime.ofEpochSecond(dto.getStartTime(), 0, java.time.ZoneOffset.ofHours(8));
            endTime = LocalDateTime.ofEpochSecond(dto.getEndTime(), 0, java.time.ZoneOffset.ofHours(8));
        }
        
        log.info("startTime:{}",startTime);
        log.info("endTime:{}",endTime);
        
        //查询数据库相同范围的数据
        LambdaQueryWrapper<DeviceData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.between(DeviceData::getAlarmTime, startTime, endTime);
        // 如果指定了功能ID，添加过滤条件
        if (StringUtils.isNotEmpty(dto.getFunctionId())) {
            queryWrapper.eq(DeviceData::getFunctionId, dto.getFunctionId());
        }
        // 如果指定了设备ID，添加过滤条件
        if (StringUtils.isNotEmpty(dto.getIotId())) {
            queryWrapper.eq(DeviceData::getIotId, dto.getIotId());
        }
        List<DeviceData> deviceDataList = deviceDataMapper.selectList(queryWrapper);
        log.info("deviceDataList:{}",deviceDataList);
        
        // 如果没有数据，查询一下数据库中的总数据量
        if (deviceDataList.isEmpty()) {
            log.info("查询结果为空，检查数据库中是否有数据...");
            Long totalCount = deviceDataMapper.selectCount(null);
            log.info("数据库中总数据量: {}", totalCount);
            
            // 查询最近的几条数据
            LambdaQueryWrapper<DeviceData> recentQuery = new LambdaQueryWrapper<>();
            recentQuery.orderByDesc(DeviceData::getAlarmTime).last("LIMIT 5");
            List<DeviceData> recentData = deviceDataMapper.selectList(recentQuery);
            log.info("最近5条数据: {}", recentData);
            
            // 查询指定设备的数据
            LambdaQueryWrapper<DeviceData> deviceQuery = new LambdaQueryWrapper<>();
            deviceQuery.eq(DeviceData::getIotId, dto.getIotId());
            List<DeviceData> deviceData = deviceDataMapper.selectList(deviceQuery);
            log.info("设备 {} 的数据量: {}", dto.getIotId(), deviceData.size());
        }
        //将deviceDataList转换为DeviceDataListByDayRequestVo
        //返回完整的24小时数据数组，索引0-23分别对应00:00-23:00
        
        // 按小时分组，格式为 "HH:00" (如: "18:00", "19:00")
        Map<String, List<DeviceData>> groupedByHour = deviceDataList.stream()
            .collect(Collectors.groupingBy(d -> d.getAlarmTime().format(DateTimeFormatter.ofPattern("HH:00"))));
        
        // 创建固定长度24小时的数组
        List<DeviceDataListByDayRequestVo> deviceDataListByDayRequestVoList = new ArrayList<>();
        
        // 生成00:00到23:00的完整24小时数据
        for (int hour = 0; hour < 24; hour++) {
            String hourTime = String.format("%02d:00", hour); // "00:00", "01:00", ..., "23:00"
            
            DeviceDataListByDayRequestVo vo = new DeviceDataListByDayRequestVo();
            vo.setDateTime(hourTime);
            
            // 检查该小时是否有数据
            if (groupedByHour.containsKey(hourTime)) {
                List<DeviceData> hourDataList = groupedByHour.get(hourTime);
                
                // 计算该小时内所有数据的平均值
                double avgValue = hourDataList.stream()
                    .mapToDouble(d -> {
                        try {
                            return Double.parseDouble(d.getDataValue());
                        } catch (NumberFormatException e) {
                            log.warn("无法解析数据值: {}, 跳过该值", d.getDataValue());
                            return 0.0;
                        }
                    })
                    .average()
                    .orElse(0.0);
                
                vo.setDataValue((long) avgValue); // 截断小数部分
            } else {
                // 该小时没有数据，设置为0
                vo.setDataValue(0L);
            }
            
            deviceDataListByDayRequestVoList.add(vo);
        }
        log.info("deviceDataListByDayRequestVoList:{}",deviceDataListByDayRequestVoList);
        return deviceDataListByDayRequestVoList;
    }

    /**
     * 按周统计查询指标数据
     * @param dto
     * @return
     */
    @Override
    public List<DeviceDataListByWeekRequestVo> queryDeviceDataListByWeek(DeviceDataListByDayRequestDto dto) {
        log.info("dto:{}",dto);
        // 判断时间戳是秒级还是毫秒级
        LocalDateTime startTime, endTime;
        if (dto.getStartTime() > 1000000000000L) {
            // 毫秒级时间戳
            startTime = LocalDateTime.ofEpochSecond(dto.getStartTime() / 1000, 0, java.time.ZoneOffset.ofHours(8));
            endTime = LocalDateTime.ofEpochSecond(dto.getEndTime() / 1000, 0, java.time.ZoneOffset.ofHours(8));
        } else {
            // 秒级时间戳
            startTime = LocalDateTime.ofEpochSecond(dto.getStartTime(), 0, java.time.ZoneOffset.ofHours(8));
            endTime = LocalDateTime.ofEpochSecond(dto.getEndTime(), 0, java.time.ZoneOffset.ofHours(8));
        }
        
        log.info("startTime:{}",startTime);
        log.info("endTime:{}",endTime);
        
        //查询数据库相同范围的数据
        LambdaQueryWrapper<DeviceData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.between(DeviceData::getAlarmTime, startTime, endTime);
        // 如果指定了功能ID，添加过滤条件
        if (StringUtils.isNotEmpty(dto.getFunctionId())) {
            queryWrapper.eq(DeviceData::getFunctionId, dto.getFunctionId());
        }
        // 如果指定了设备ID，添加过滤条件
        if (StringUtils.isNotEmpty(dto.getIotId())) {
            queryWrapper.eq(DeviceData::getIotId, dto.getIotId());
        }
        List<DeviceData> deviceDataList = deviceDataMapper.selectList(queryWrapper);
        log.info("deviceDataList:{}",deviceDataList);
        
        // 如果没有数据，查询一下数据库中的总数据量
        if (deviceDataList.isEmpty()) {
            log.info("查询结果为空，检查数据库中是否有数据...");
            Long totalCount = deviceDataMapper.selectCount(null);
            log.info("数据库中总数据量: {}", totalCount);
            
            // 查询最近的几条数据
            LambdaQueryWrapper<DeviceData> recentQuery = new LambdaQueryWrapper<>();
            recentQuery.orderByDesc(DeviceData::getAlarmTime).last("LIMIT 5");
            List<DeviceData> recentData = deviceDataMapper.selectList(recentQuery);
            log.info("最近5条数据: {}", recentData);
            
            // 查询指定设备的数据
            LambdaQueryWrapper<DeviceData> deviceQuery = new LambdaQueryWrapper<>();
            deviceQuery.eq(DeviceData::getIotId, dto.getIotId());
            List<DeviceData> deviceData = deviceDataMapper.selectList(deviceQuery);
            log.info("设备 {} 的数据量: {}", dto.getIotId(), deviceData.size());
        }
        //将deviceDataList转换为DeviceDataListByWeekRequestVo
        //应该是："dateTime": "01.15", 只显示月份和日期，并且是24小时制
        //在这里应该应该是查出来的数据，然后根据日期时间进行分组，然后计算出每个日期时间的平均值
        //然后返回一个List<DeviceDataListByWeekRequestVo>
        //DeviceDataListByWeekRequestVo的dateTime是月份和日期，dataValue是平均值
        DeviceDataListByWeekRequestVo deviceDataListByWeekRequestVo = new DeviceDataListByWeekRequestVo();
        //List<DeviceData> deviceDataList = deviceDataMapper.selectList(queryWrapper);

        // 按天分组，计算平均值
        Map<String, List<DeviceData>> grouped = deviceDataList.stream()
            .collect(Collectors.groupingBy(d -> d.getAlarmTime().format(DateTimeFormatter.ofPattern("MM.dd"))));

        List<DeviceDataListByWeekRequestVo> result = new ArrayList<>();
        
        // 生成完整的日期范围（从startTime到endTime的每一天）
        LocalDate currentDate = startTime.toLocalDate();
        LocalDate endDate = endTime.toLocalDate();
        
        log.info("开始日期: {}, 结束日期: {}", currentDate, endDate);
        log.info("已有数据的日期: {}", grouped.keySet());
        
        while (!currentDate.isAfter(endDate)) {
            String dateStr = currentDate.format(DateTimeFormatter.ofPattern("MM.dd"));
            log.info("处理日期: {}", dateStr);
            
            DeviceDataListByWeekRequestVo vo = new DeviceDataListByWeekRequestVo();
            vo.setDateTime(dateStr);
            
            // 检查当天是否有数据
            if (grouped.containsKey(dateStr)) {
                List<DeviceData> dayList = grouped.get(dateStr);
                // 计算平均值
                double avg = dayList.stream()
                    .mapToDouble(d -> {
                        try {
                            return Double.parseDouble(d.getDataValue());
                        } catch (Exception e) {
                            return 0.0;
                        }
                    })
                    .average()
                    .orElse(0.0);
                // 只保留整数部分（直接截断，不四舍五入）
                vo.setDataValue((long) avg);
                log.info("日期 {} 有数据，平均值: {}", dateStr, vo.getDataValue());
            } else {
                // 当天没有数据，设置为0
                vo.setDataValue(0L);
                log.info("日期 {} 无数据，设置为0", dateStr);
            }
            
            result.add(vo);
            currentDate = currentDate.plusDays(1);
        }
        
        log.info("最终生成的结果数量: {}", result.size());
        
        // 如果结果数量小于预期，强制补充缺失的日期（临时调试）
        if (result.size() < 7) {
            log.warn("结果数量不足7天，当前数量: {}, 开始补充缺失日期", result.size());
            
            // 创建一个完整的7天日期列表进行比较
            List<String> allDates = new ArrayList<>();
            LocalDate checkDate = startTime.toLocalDate();
            for (int i = 0; i < 7; i++) {
                allDates.add(checkDate.format(DateTimeFormatter.ofPattern("MM.dd")));
                checkDate = checkDate.plusDays(1);
            }
            log.info("期望的完整日期列表: {}", allDates);
            
            Set<String> existingDates = result.stream()
                .map(DeviceDataListByWeekRequestVo::getDateTime)
                .collect(Collectors.toSet());
            log.info("实际存在的日期: {}", existingDates);
        }
        
        // 结果已经按照日期顺序生成，不需要额外排序
        log.info("deviceDataListByWeekRequestVo:{}", result);
        return result;
    }

    /**
     * 添加老人
     * @param dto
     * @return
     */
    @Override
    public Boolean addElder(AddElderRequestDto dto) {
        // 1. 获取当前登录的家属用户ID
        Long familyMemberId = UserThreadLocal.getUserId();
        if (familyMemberId == null) {
            throw new RuntimeException("用户未登录");
        }

        // 2. 检查身份证号是否已存在
        LambdaQueryWrapper<Elder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Elder::getIdCardNo, dto.getIdCard());
        Elder existingElder = elderMapper.selectOne(wrapper);
        
        Long elderId;
        if (existingElder != null) {
            // 老人已存在，使用现有的老人ID
            elderId = existingElder.getId();
            if(!Objects.equals(dto.getName(), existingElder.getName())){
                throw new BaseException("老人姓名填写错误");
            }
        } else {
            throw new BaseException("老人不存在");
        }

        // 4. 检查家属和老人的关联关系是否已存在
        LambdaQueryWrapper<FamilyMemberElder> relationWrapper = new LambdaQueryWrapper<>();
        relationWrapper.eq(FamilyMemberElder::getFamilyMemberId, familyMemberId)
                      .eq(FamilyMemberElder::getElderId, elderId);
        FamilyMemberElder existingRelation = familyMemberElderMapper.selectOne(relationWrapper);

        if (existingRelation == null) {
            // 5. 创建家属和老人的关联关系
            FamilyMemberElder familyMemberElder = new FamilyMemberElder();
            familyMemberElder.setFamilyMemberId(familyMemberId);
            familyMemberElder.setElderId(elderId);
            familyMemberElder.setRemark(dto.getRemark());
            familyMemberElderMapper.insert(familyMemberElder);
        }

        return true;
    }

    /**
     * 查询家人列表
     * @return
     */
    @Override
    public List<FamilyElderListVo> getMyElderList() {
        // 1. 获取当前登录的家属用户ID
        Long familyMemberId = UserThreadLocal.getUserId();
        if (familyMemberId == null) {
            throw new RuntimeException("用户未登录");
        }

        // 2. 查询家属关联的老人列表
        List<FamilyMemberElderVo> familyMemberElders = familyMemberElderMapper.selectByMemberId(familyMemberId);
        
        // 3. 转换为响应VO
        List<FamilyElderListVo> result = new ArrayList<>();
        for (FamilyMemberElderVo item : familyMemberElders) {
            FamilyElderListVo vo = new FamilyElderListVo();
            vo.setId(item.getId());
            vo.setFamilyMemberId(item.getFamilyMemberId());
            vo.setElderId(item.getElderId());
            vo.setElderName(item.getElderName());
            result.add(vo);
        }
        
        return result;
    }

    /**
     * 分页查询家人列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public List<MemberElderVo> getMyElderListByPage(Integer pageNum, Integer pageSize) {
        // 1. 获取当前登录的家属用户ID
        Long familyMemberId = UserThreadLocal.getUserId();
        if (familyMemberId == null) {
            throw new RuntimeException("用户未登录");
        }

        // 2. 查询家属关联的老人列表（包含详细信息）
        // 注意：这里暂时不做真正的分页，直接返回所有数据
        // 如果需要真正的分页，可以考虑使用MyBatis-Plus的分页插件
        List<MemberElderVo> result = familyMemberElderMapper.listByPage(familyMemberId);
        
        return result;
    }

    /**
     * 手动解析设备数据JSON，处理JSON解析异常
     */
    private List<DeviceData> parseDeviceDataManually(String jsonStr) {
        List<DeviceData> result = new ArrayList<>();
        try {
            // 使用Jackson ObjectMapper进行解析，配置时间格式
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.registerModule(new JavaTimeModule());
            objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
            objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            
            // 解析JSON数组
            if (jsonStr.trim().startsWith("[")) {
                DeviceData[] dataArray = objectMapper.readValue(jsonStr, DeviceData[].class);
                result = Arrays.asList(dataArray);
            } else if (jsonStr.trim().startsWith("{")) {
                DeviceData data = objectMapper.readValue(jsonStr, DeviceData.class);
                result = Arrays.asList(data);
            }
            
            log.info("手动解析结果：解析出 {} 条数据", result.size());
            
        } catch (Exception e) {
            log.error("手动解析JSON时发生异常: {}", e.getMessage(), e);
            
            // 如果Jackson也失败，尝试使用JSONObject手动解析
            try {
                log.info("尝试使用JSONObject手动解析...");
                result = parseDeviceDataWithJSONObject(jsonStr);
            } catch (Exception ex) {
                log.error("JSONObject解析也失败: {}", ex.getMessage());
            }
        }
        
        return result;
    }
    
    /**
     * 使用JSONObject手动解析设备数据
     */
    private List<DeviceData> parseDeviceDataWithJSONObject(String jsonStr) {
        List<DeviceData> result = new ArrayList<>();
        
        try {
            // 使用hutool的JSONUtil解析为JSONArray
            cn.hutool.json.JSONArray jsonArray;
            if (jsonStr.trim().startsWith("[")) {
                jsonArray = JSONUtil.parseArray(jsonStr);
            } else {
                jsonArray = JSONUtil.parseArray("[" + jsonStr + "]");
            }
            
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            
            for (int i = 0; i < jsonArray.size(); i++) {
                cn.hutool.json.JSONObject jsonObject = jsonArray.getJSONObject(i);
                
                DeviceData deviceData = new DeviceData();
                deviceData.setIotId(jsonObject.getStr("iotId"));
                deviceData.setDeviceName(jsonObject.getStr("deviceName"));
                deviceData.setProductKey(jsonObject.getStr("productKey"));
                deviceData.setProductName(jsonObject.getStr("productName"));
                deviceData.setFunctionId(jsonObject.getStr("functionId"));
                deviceData.setAccessLocation(jsonObject.getStr("accessLocation"));
                deviceData.setLocationType(jsonObject.getInt("locationType"));
                deviceData.setPhysicalLocationType(jsonObject.getInt("physicalLocationType"));
                deviceData.setDeviceDescription(jsonObject.getStr("deviceDescription"));
                deviceData.setDataValue(jsonObject.getStr("dataValue"));
                
                // 手动解析时间
                String alarmTimeStr = jsonObject.getStr("alarmTime");
                if (StringUtils.isNotEmpty(alarmTimeStr)) {
                    LocalDateTime alarmTime = LocalDateTime.parse(alarmTimeStr, formatter);
                    deviceData.setAlarmTime(alarmTime);
                }
                
                result.add(deviceData);
            }
            
            log.info("JSONObject手动解析成功：解析出 {} 条数据", result.size());
            
        } catch (Exception e) {
            log.error("JSONObject手动解析失败: {}", e.getMessage(), e);
        }
        
        return result;
    }
}
